$(document).ready(function(){
	$(".swiper-container").swiper({
     loop: true,
     autoplay: 3000
    });
	
    $('.spinner').spinner({min:1});
    
	var skuCombinations = $("#skuCombinationsStr").val();
	var goodsId = $("#goods_id").val();
	var skuId = $("#sku_id").val();
	//是否赠品
	var isGift = $("#sku_state").val()==3; 
	//缺货标识
	var outOfStockFlag = false;
	//请求总库存
	$.ajax({
		url:appPath+'/goodsSku/getInventoryAndIncreaseClick.json',
		type:'post',
		dataType:'json',
		data:{"goodsId":goodsId,"skuId":skuId},
		success:function(inventory){
			//$.alert(inventory);
			if(inventory<=0){
				outOfStockFlag = true;
			}
			$("#sku_inventory").val(inventory);
			$("#sku_inventory_em").text(inventory);
		},
		error:function(){
			//$.alert("系统异常!");
		}
	});	
	//获取价格列表
	$.ajax({
		url:appPath+'/goodsSku/getSkuPrices.html',
		type:'post',
		dataType:'html',
		data:{"skuId":skuId,"token":$.cookie("token")},
		success:function(skuPricesInfo){
			$("#sku_prices_div").html(skuPricesInfo);
		},
		error:function(){
			//$.alert("系统异常!");
		}
	});	
	$("#footer_space_div").height($("#tabm_div").height());
	/**
	 * 记录scrollTop
	 */
	function recordScroll(){
		try{
			var scrollTop =  $("body").scrollTop();
			sessionStorage.setItem("specClickFlag","1");
			sessionStorage.setItem("detailSpecScrollTop",scrollTop);
		}catch(e){
			
		}
	}
	/**
	 * 还原scrollTop
	 */
	function revertScroll(){
		try{
			var sceneFlag = sessionStorage.getItem("specClickFlag");
			//detailBackFlag = sessionStorage.getItem("detailBackFlag");
			var detailSpecScrollTop = sessionStorage.getItem("detailSpecScrollTop");
			if("1"==sceneFlag){
				$("body").animate({scrollTop: detailSpecScrollTop}, 0);
				sessionStorage.removeItem("specClickFlag");
				//sessionStorage.removeItem("detailBackFlag");
				sessionStorage.removeItem("detailSpecScrollTop");
			}
		}catch(e){

		}
	}
	function getSkuId(_this){
		$(_this).parent().children(".weui_btn_primary").removeClass("weui_btn_primary");
		$(_this).addClass("weui_btn_primary");
		//规格格式（规格类名id:规格值id;规格类名id:规格值id）
		checkAndDisableSpec($(_this).attr("id"));
		var specCombinationStr ="";
		var specCombinationNameStr ="";
		$(".goodsSpec").each(function(){
			var specId = $(this).attr("specId");
			var specValueId = $($(this).children(".weui_btn_primary")[0]).attr("specValueId");
			specCombinationStr+=specId+":"+specValueId+";";
			var specName =$(this).attr("specName");;
			var specValueName = $($(this).children(".weui_btn_primary")[0]).attr("specValueName");
			specCombinationNameStr+=specName+":"+specValueName+";";
		});
		specCombinationStr = specCombinationStr.substr(0,specCombinationStr.length-1);
		specCombinationNameStr = specCombinationNameStr.substr(0,specCombinationNameStr.length-1);
		var temArr = skuCombinations.split(specCombinationStr);
		if(temArr.length==1){
			$("#choosedSpecCombination").text(specCombinationNameStr+" 该规格缺货！");
			//缺货标识
			outOfStockFlag = true;
			return ;
		}
		$("#choosedSpecCombination").text(specCombinationNameStr);
		var temArr = temArr[0].split(",{");
		var idStr = temArr[temArr.length-1];
		var matchResult = idStr.match("\\d+");
		var skuId =matchResult[0];
		//$(_this).attr("href",appPath+"/"+skuId+".html");
		recordScroll();
		location.replace(appPath+"/"+skuId+".html");
	}
	
	var skuCombina = $("#goodsSkuSpecId").val();
	var combinaArr= skuCombina.split(";");
	for(var i=0;i<combinaArr.length;i++){
		var speInfoArr = combinaArr[i].split(":");
		var temId ="#spceValue"+speInfoArr[1];
		$("#spceValue"+speInfoArr[1]).addClass("weui_btn_primary");
	}
	var skuCombinationsJson = null;
	if(skuCombinations!=null&&skuCombinations!=""){
		skuCombinationsJson = eval("("+skuCombinations+")")
	}
	//规格map 每个规格值为key specId:valueId
	//var specMap = new Map();
	var specMap = {};
	if(skuCombinationsJson!=null){
		for(var skuCombina in skuCombinationsJson){
			var specCombina = skuCombinationsJson[skuCombina].specId;
			var specArr = specCombina.split(";");
			for(var spec in specArr){
				var key = specArr[spec];
				//var tem = specMap.get(key);
				var tem = specMap[key];
				if(tem==null||tem.length==0){
					tem = new Array();
				}
				tem.push(specCombina);
				//specMap.set(key,tem);
				specMap[key] = tem;
			}
		}
	}
	//disabled规格
	function checkAndDisableSpec(specValueDomId){
		var specId = $("#"+specValueDomId).parent().attr("specId");
		var specValueId = $("#"+specValueDomId).attr("specValueId");
		specCombinationKey = specId+":"+specValueId;
		//有效的sku规格组合
		//var temArr = specMap.get(specCombinationKey);
		var temArr = specMap[specCombinationKey];
		if(temArr==undefined||temArr==null){
			return false;
		}
		$("#"+specValueDomId).parent().removeClass("spec-hl-bg");
		$(".goodsSpec").each(function(){
			var temSpecId = $(this).attr("specId");
			//if (temSpecId != specId) {// 不是同一个规格分类才验证
			$(this).find(".spec").removeClass("em_disabled");
			var specArr = $(this).children("a");
			for (var i=0;i<specArr.length;i++ ) {
				var temSpecValueId = $(specArr[i]).attr("specValueId");
				var specStr = temSpecId + ":" + temSpecValueId;
				if (temSpecId != specId){
					var includeFlag = false;
					for ( var j=0;j<temArr.length;j++) {
						if (temArr[j].indexOf(specStr) > -1) {//有，直接退出循环
							includeFlag = true;
							break;
						}
					}
					if(!includeFlag){// 该规格值没有,设置disabaled
						$(specArr[i]).addClass("em_disabled");
						$(specArr[i]).removeClass("weui_btn_primary");
					}
				}else if(specMap[specStr]==undefined||specMap[specStr]==null){
					$(specArr[i]).addClass("em_disabled");
					$(specArr[i]).removeClass("weui_btn_primary");
				}
			}
			//}
		});
		//若无选中，整行
		$(".em_disabled").each(function(){
			if($(this).parent().find(".weui_btn_primary").length==0){//如果当前spec未选，设置
				$(this).parent().addClass("spec-hl-bg");
				outOfStockFlag = true;
			}
		});
		return true;
	}
	$(".spec.weui_btn_primary").each(function(){
		checkAndDisableSpec($(this).attr("id"));
	});
	$(".spec").click(function(){
		if($(this).hasClass("em_disabled")){
			return;
		}
		if($(this).hasClass("weui_btn_primary")){
			return;
		}
		getSkuId(this);
	});
	//定位scroll
	revertScroll();
	/**
	 *加入购物车
	 */
	$("#save_in_cart").click(function(){
		//var goodsId = $("#goods_id").val();
		if(isGift){
			$.alert("该商品为赠品，不能购买！");
			return false;
		}
		if(!checkBuyNumGtInventory()){
			$.alert("购买数量大于商品库存！");
			return false;
		}
		if(outOfStockFlag){
			$.alert("商品缺货，无法进行此操作！");
			return false;
		}
		if(limitTimeFlag){
			$.alert("商品不在限购时段内！");
			return false;
		}
		var skuId = $("#sku_id").val();
		var num = $("#goods_num").val();
		var isBuy =0;
		//加入购物车 操作
		var optionType =1;
		modifyCartItemsCookie(skuId, num,isBuy, optionType);
	});
	/**
	 * 跳转购物车
	 */
	$("#cart_link").click(function(){
		var url = appPath+"/cart/list.html";
		$(this).attr("href",url);
		
	});
	//添加收藏
	$("#save_favorite").click(function(){
		var goodsId = $("#goods_id").val();
		var skuId = $("#sku_id").val();
		$.ajax({
			url:appPath+'/favorites/save.html',
			type:'post',
			dataType:'json',
			data:{"goodsId":goodsId,"skuId":skuId,"token":$.cookie("token")},
			success:function(result){
				if(result.code=="-1"){
					var loginUrl=appPath+"/member/login.html"; 
					self.location=loginUrl;
				}else if(result.code=="1"){//成功
					$.alert(result.msg);
				}else{//失败
					$.alert(result.msg);
				}
			},
			error:function(){
				$.alert("系统异常!");
			}
		});	
	});
	//单品购买
	$("#single_buy").click(function(){
		if(isGift){
			$.alert("该商品为赠品，不能购买！");
			return false;
		}
		if(!checkBuyNumGtInventory()){
			$.alert("购买数量大于商品库存！");
			return false;
		}
		if(outOfStockFlag){
			$.alert("商品缺货，无法进行此操作！");
			return false;
		}
		if(limitTimeFlag){
			$.alert("商品不在限购时段内！");
			return false;
		}
		var url=appPath+"/order/preOrderInfo.html";
		var skuId = $("#sku_id").val();
		var token = $.cookie("token");
		var temGoodsNum =$("#goods_num").val();
		//var singleBuyFlag=1;
		// cartId-skuId-num-isBuy-isDel
		var singleBuyInfo = "-"+skuId+"-"+temGoodsNum+"-"+1+"-0";
		self.location=url+"?token="+token+"&singleBuyFlag=1&singleBuyInfo="+singleBuyInfo;
	});
	//积分兑换
	$("#point_buy").click(function(){
		if(!isGift){
			$.alert("该商品不为积分兑换商品！");
			return false;
		}
		if(!checkBuyNumGtInventory()){
			$.alert("购买数量大于商品库存！");
			return false;
		}
		if(outOfStockFlag){
			$.alert("商品缺货，无法进行此操作！");
			return false;
		}
		if(limitTimeFlag){
			$.alert("商品不在限购时段内！");
			return false;
		}
		//判断用户积分
		var url=appPath+"/order/preOrderInfo.html";
		var skuId = $("#sku_id").val();
		var token = $.cookie("token");
		var temGoodsNum =$("#goods_num").val();
		//var singleBuyFlag=1;
		// cartId-skuId-num-isBuy-isDel
		var singleBuyInfo = "-"+skuId+"-"+temGoodsNum+"-"+1+"-0";
		self.location=url+"?token="+token+"&singleBuyFlag=2&singleBuyInfo="+singleBuyInfo;
	});
	/*var goodsNum = 1;
	function checkInventory(){
		var temGoodsNum =$("#goods_num").val();
		var inventory = $("#sku_inventory").val();
		if(parseInt(temGoodsNum)>parseInt(inventory)){//设为原值
			$("#goods_num").val(goodsNum);
			return false;
		}
		$("#goods_num").val(temGoodsNum);
		goodsNum = temGoodsNum;
		return true;
	}
	$(".spinner").change(function(){
		checkInventory();
	});
	$(".spinner button").click(function(){
		checkInventory();
	});*/
	
	var title=$('title').text();
	var url=window.location.href;
	var image=$("[data-swiper-slide-index='0'] img:first").attr('src');
	
	if (/(applewebkitapp)/i.test(navigator.userAgent)) {
		$("#share_link").hide();
		$("#share_app").show();
		 document.querySelector('#share_app').onclick = function () {
			 window.location = 'js-call:weixin_share:'+ encodeURIComponent(JSON.stringify({title : title,url : url,image : image}));
		 }
	} else if (/(androidapp)/i.test(navigator.userAgent)) {
		$("#share_link").hide();
		$("#share_app").show();
	 	document.querySelector('#share_app').onclick = function () {
	 		window.Weixin.weixin_share(title,url,image);
		 }
	} else {
		
	}
	
	if(is_weixn()){
		$("#share_link").hide();
		$("#share_app").show();
	}
	$("#share_img").click(function(){
		$("#share_div").show();
	});
	$("#share_hide").click(function(){
		$("#share_div").hide();
	});
	//ueditor js
	uParse('#detail', {
	    rootPath: appPath+'/js/ueditor'
	})
	if($("#time_span").length>0){
		initTime = $("#goods_time_info_sec").val();
		limitState = $("#goods_time_info_state").val();
		//console.log(initTime);
		if(limitState!=3){
			if(limitState==1){//未开始
				limitTimeFlag = true;
			}
			startCalculateTime();
		}else{
			limitTimeFlag = true;
		}
		//var limitTimer  = setTimeout("startCalculateTime()",1000);
	}
	if(is_weixn()){
		$("img.lazy-img").lazyload({
			event : "sporty"
		});
		$(window).bind("load", function() {
			var timeout = setTimeout(function() {
				$("img.lazy-img").trigger("sporty")
			}, 500);
		});
	}else{
		$("img.lazy-img").lazyload({
			threshold : 100
		});
	}
});
//限时标志
var limitTimeFlag = false;
var initTime = 0;
var limitState = "";
var limitTimer ="";
/**
 * 限时购计时
 */
function startCalculateTime(){
	initTime = initTime -1000;
	var secs = Math.floor(initTime/1000);
	limitTimer = setTimeout("startCalculateTime()",1000);
	if(secs<=0){
		if(limitState==2){
			limitTimeFlag = true;
			clearTimeout(limitTimer);
			$(".limit_msg").text("抢购已结束");
		}
	}
	var mins = Math.floor(secs/60);
	var hours = Math.floor(mins/60);
	var days = Math.floor(hours/24);
	var timeStr = days+"天"+hours%24+"小时"+mins%60+"分钟"+secs%60+"秒";
	$("#time_span").text(timeStr);
}

function checkBuyNumGtInventory(){
	var inventory = $("#sku_inventory").val();
	var num = $("#goods_num").val();
	return inventory-num>=0;
}
/**
 * 返回并记录返回操作
 */
function backAndRecord(){
	//记录详情页返回
	try{
		//window.sessionStorage.setItem("detailBackFlag","1");
	}catch(e){
		//
	}
	//window.history.go(-1);
}